package com.example.esaclient;


import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Request.Callback;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.test.PerformanceTestCase;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class AddSocialActivity extends Activity {

	 // Constants
    /**
     * Register your  app here https://dev.twitter.com/apps/new
     *  and get your consumer key and secret
     * */
    static String TWITTER_CONSUMER_KEY = "RUMoRPLvEHqN9dPoFIiwQ";
    static String TWITTER_CONSUMER_SECRET = "krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE";
 
    // Preference Constants
    static String PREFERENCE_NAME = "twitter_oauth";
    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
    static final String PREF_KEY_TWITTER_USERNAME = "key_tw_user";
    static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
    static final String PREF_KEY_FACEBOOK_USERNAME = "key_fb_user";
    static final String PREF_KEY_GOOGLE_LOGIN = "isGoogleLogedIn";
    static final String PREF_KEY_GOOGLE_USERNAME = "key_gp_user";
 
    static final String TWITTER_CALLBACK_URL   = "esaclient://callback";
 
    // Twitter oauth urls
 // Twitter oauth urls
    static final String URL_TWITTER_AUTH = "auth_url";
    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
    public Integer esaUsrID;
 
    // Progress dialog
    ProgressDialog pDialog;
 
    //Facebook manager
    private Facebook fb; 
    
    // Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;
     
    // Shared Preferences
    private static SharedPreferences mSharedPreferences;
     
    //Twitter AccessToken
    AccessToken accessToken;
    
    // Internet Connection detector
    private ConnectionDetector cd;
     
    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();
 
    //progress dialog for esa communication
    ProgressDialog dialog;
    public String TWusername; 
    public String FBusername; 
    public String GPusername; 
    public Boolean TWlogged=false;
    public Boolean FBlogged=false;
    public Boolean GPlogged=false;
 
    //layout resources
    TextView txtTWuser;
    ImageButton bttTW;
    TextView txtFBuser;
    ImageButton bttFB;
    TextView txtGPuser;
    ImageButton bttGP;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tw_access);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
         
        esaUsrID= new GlobalSettings(this).getPrefInt(GlobalSettings.PREF_ESA_USRID);
        
        //setting layout resources
        txtTWuser= (TextView)findViewById(R.id.txtTWuser);
        bttTW   = (ImageButton) findViewById(R.id.bttTW);
        txtFBuser= (TextView)findViewById(R.id.txtFBuser);
        bttFB   = (ImageButton) findViewById(R.id.bttFB);
        txtGPuser= (TextView)findViewById(R.id.txtGPuser);
        bttGP   = (ImageButton) findViewById(R.id.bttGP);
        
        
        cd = new ConnectionDetector(getApplicationContext());
 
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(AddSocialActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
         
        // Check if twitter keys are set
        if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
            // Internet Connection is not present
            alert.showAlertDialog(AddSocialActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
            // stop executing code by return
            return;
        }
 
     
        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
        
        /** This if conditions is tested once is
         * redirected from twitter page. Parse the uri to get oAuth
         * Verifier
         * */
        if (!isTwitterLoggedInAlready()) {
        	
        	bttTW.setBackgroundResource(R.drawable.tw_icon_off);
        	 txtTWuser.setText("Not logged in");
        	 
        	  Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
     
                try {
                    // Get the access token
                    accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
                    			
                    //Getting Twitter username
                    long userID = accessToken.getUserId();
                    
                    User user = twitter.showUser(userID);
                   
                    TWusername = user.getName();
                    String profilePic = user.getBiggerProfileImageURLHttps();
                
                    Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
                    
                   
                	dialog = ProgressDialog.show(AddSocialActivity.this, "", "Contacting Esa Server. Please, Wait...", true);
                	dialog.show();                   
                    //Calling the webService for store the AccessToken
                    new InsertToken(this).execute(esaUsrID, accessToken.getToken()+";"+accessToken.getTokenSecret(), "Twitter",Uri.encode(TWusername), profilePic);
                    
                } catch (Exception e) {                    
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }}
                }
        else{
        	//getting Twitter username from shared Prefs
        	TWusername= mSharedPreferences.getString(PREF_KEY_TWITTER_USERNAME, "");
        	bttTW.setBackgroundResource(R.drawable.tw_icon);
        	 txtTWuser.setText("Logged in as "+ TWusername);
        	TWlogged=true;
        }
        
   if (!isFacebookLoggedInAlready()) {
        	
        	bttFB.setBackgroundResource(R.drawable.fb_icon_off);
        	 txtFBuser.setText("Not logged in");
           }
        else{
        	//getting FB username from shared Prefs
        	FBusername= mSharedPreferences.getString(PREF_KEY_FACEBOOK_USERNAME, "");
        	bttFB.setBackgroundResource(R.drawable.fb_icon);
        	 txtFBuser.setText("Logged in as "+ FBusername);
        	FBlogged=true;
        }
        
        
            }
            
    
    /**
     * Function to login facebook
     * */
    public void loginToFacebook(View view) {
    
    	 // Check if already logged in
        if (!isFacebookLoggedInAlready()) { 
    	 Session.openActiveSession(this, true, new Session.StatusCallback() {

   	      // callback when session changes state
   	      @Override
   	      public void call(final Session session, SessionState state, Exception exception) {
   	    	  
   	    	  /*******WARNING!****************
   	    	   * every time you change a developing computer, you need to insert the machine key hash into the facebook application page!
   	    	   * Uncomment these lines of codes to retrieve the key hash
   	    	   *******************************/
   	    	 // -- print out the key hash --  
   			/*   try {
   			        PackageInfo info = getPackageManager().getPackageInfo(
   			                "com.example.esaclient", 
   			                PackageManager.GET_SIGNATURES);
   			        for (Signature signature : info.signatures) {
   			            MessageDigest md = MessageDigest.getInstance("SHA");
   			            md.update(signature.toByteArray());
   			            Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
   			            }
   			    } catch (NameNotFoundException e) {

   			    } catch (NoSuchAlgorithmException e) {

   			    }
   	    	  */
   	        
   	        if (session.isOpened()) {
   	     	 fb =new Facebook("336794829783831");
	        	fb.authorize(AddSocialActivity.this, new String[] {  "read_stream" ,"manage_pages", "publish_stream","publish_actions","status_update", "read_insights"}, new LoginDialogListener());
   	        	 Log.e( "APP TOKEN =>" ,session.getAccessToken());
   	    
   	        final  String token =  session.getAccessToken();
   	        
   	        //get user pages
   	     String grapPath = "me/accounts";
			Bundle params = new Bundle();
			
			params.putString("fileds", "name,access_token");

			Request request = new Request(session, grapPath,
					params, HttpMethod.GET, new Callback() {

						@Override
						public void onCompleted(Response response) {
							if (response != null) {
								final ArrayList<String> items = new ArrayList<String>();
								final ArrayList<String> tokens = new ArrayList<String>();
								final ArrayList<String> ids = new ArrayList<String>();
								items.add("Use Profile Page");
								tokens.add(token);
								ids.add("0");
								GraphObject graphObject = response.getGraphObject();
								JSONObject  jsonObject = graphObject.getInnerJSONObject();
								 JSONArray array;
				    				try {
				    					array = jsonObject.getJSONArray("data");		    			
				    			
				                     for (int i = 0; i < array.length(); i++) {				              
				                         JSONObject object = (JSONObject) array.get(i); 
				                         items.add((String)object.get("name"));				      
				                         tokens.add ((String)object.get("access_token"));		
				                         ids.add((String)object.get("id"));		
				                     }}
				    			 catch (JSONException e) {

			    	                      e.printStackTrace();
			    	                     }
				                         
							
				    				  
								  
				    				CharSequence[] cs = items.toArray(new CharSequence[items.size()]);
								AlertDialog.Builder builder = new AlertDialog.Builder(AddSocialActivity.this);
				        	    builder.setTitle("Choose a page")
				        	           .setItems(cs, new DialogInterface.OnClickListener() {
				        	               public void onClick(DialogInterface dialog, int which) {
				        	            	   
				        	            	   if(which==0){//is the User profile
				        	            		   
				        	            	          // make request to the /me API
				        	            	          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

				        	            	            // callback after Graph API response with user object
				        	            	            @Override
				        	            	            public void onCompleted(GraphUser user, Response response) {
				        	            	              if (user != null) {
				        	            	            	 
				        	            	            	
				        	            	            	FBusername= user.getName();
				        	            	                final String profilePic= "http://graph.facebook.com/"+user.getId()+"/picture ";
				        	            	                
				        	            	              
				        	            	                new InsertToken(AddSocialActivity.this).execute(esaUsrID,token , "Facebook",Uri.encode(FBusername),Uri.encode(profilePic) );
				        	            	              }
				        	            	            }
				        	            	          });
				        	            	   }
				        	            	   else{ //is a Page
				        	            		   
				        	            		   FBusername= items.get(which);
				        	            		   final String profilePic= "http://graph.facebook.com/"+ids.get(which)+"/picture ";
				        	            		   
				        	            		   //save the pageID fot insights
				        	            		    Editor e = mSharedPreferences.edit(); 
				        	                        e.putString(GlobalSettings.PREF_KEY_FACEBOOK_ID, ids.get(which));
			        	            	            e.commit();
			        	            	            
		        	            	                new InsertToken(AddSocialActivity.this).execute(esaUsrID,tokens.get(which) , "Facebook",Uri.encode(FBusername),Uri.encode(profilePic) );
				        	            	   }
				        	               
				        	           }
				        	    });
				        	     builder.create();
				        	     builder.show();
								
							}

						}
					});

			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();
   	        
		
				
   	        
   	        
   	       
   	        }
   	      }
   	    });
        }
        else {
        	
        
        		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Are you sure you want to log out from Facebook?")
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                           	logoutFromFacebook(); 
                           	
                           }
                       })
                       .setNegativeButton("No", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               // User cancelled the dialog
                           }
                       });
                builder.create();
                builder.show();

           	
           }
        
    }
    
    
            
            /**
             * Function to login twitter
             * */
            public void loginToTwitter(View view) {
                // Check if already logged in
                if (!isTwitterLoggedInAlready()) {                     
                     ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                    builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
                    Configuration configuration = builder.build();
                     
                    TwitterFactory factory = new TwitterFactory(configuration);
                    twitter = factory.getInstance();
         
                    try {
                    	  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                          StrictMode.setThreadPolicy(policy);
                        requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                        Toast.makeText(getApplicationContext(),"Opening browser...", Toast.LENGTH_LONG).show();
                        Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()));
                        webIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);                        
                        webIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        webIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
                        this.startActivity(webIntent);
                        
                        finish();
                    } catch (TwitterException e) {
                        e.printStackTrace();
                    }
                } else {
                   
                	 AlertDialog.Builder builder = new AlertDialog.Builder(this);
                     builder.setMessage("Are you sure you want to log out from Twitter?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                	logoutFromTwitter(); 
                                	
                                }
                            })
                            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // User cancelled the dialog
                                }
                            });
                     builder.create();
                     builder.show();

                	
                }
            }
         
            /**
             * Check user already logged from shared preferences
             * 
             * */
            private boolean isTwitterLoggedInAlready() {
                // return twitter login status from Shared Preferences
                return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
            }
            private boolean isFacebookLoggedInAlready() {
                // return twitter login status from Shared Preferences
                return mSharedPreferences.getBoolean(PREF_KEY_FACEBOOK_LOGIN, false);
            }
            private boolean isGoogleLoggedInAlready() {
                // return twitter login status from Shared Preferences
                return mSharedPreferences.getBoolean(PREF_KEY_GOOGLE_LOGIN, false);
            }
            
	public void esaResult(String result) {

		if (result.equals("Twitter")) {
			if (TWlogged) { //logging out
			// Clear the shared preferences
                Editor e = mSharedPreferences.edit();
                e.remove(PREF_KEY_OAUTH_TOKEN);
                e.remove(PREF_KEY_OAUTH_SECRET);
                e.remove(PREF_KEY_TWITTER_LOGIN);
                e.remove(PREF_KEY_TWITTER_USERNAME);
                e.remove(GlobalSettings.PREF_TWITTER_TOKEN);
                e.commit();
				bttTW.setBackgroundResource(R.drawable.tw_icon_off);
				txtTWuser.setText("Not logged in.");
				TWlogged = false;
			} else { //logging in
		
			    // Shared Preferences
                Editor e = mSharedPreferences.edit(); 
                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
                e.putString(GlobalSettings.PREF_TWITTER_TOKEN, accessToken.getToken()+";"+accessToken.getTokenSecret());
                e.putString(PREF_KEY_TWITTER_USERNAME,TWusername);            
                e.putLong(GlobalSettings.PREF_KEY_LAST_SRV_UPDATE, 0); //Force updateDB on server
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes 
				bttTW.setBackgroundResource(R.drawable.tw_icon);
				txtTWuser.setText("Logged in as " + TWusername);
				TWlogged = true;
			}
		}
		else if (result.equals("Facebook")) {
			if (FBlogged) { //logging out
			// Clear the shared preferences
                Editor e = mSharedPreferences.edit();
                
                e.remove(PREF_KEY_FACEBOOK_LOGIN);
                e.remove(PREF_KEY_FACEBOOK_USERNAME);
                e.commit();
				bttFB.setBackgroundResource(R.drawable.fb_icon_off);
				txtFBuser.setText("Not logged in.");
				FBlogged = false;
			} else { //logging in
				
			    // Shared Preferences
                Editor e = mSharedPreferences.edit();               
                e.putString(PREF_KEY_FACEBOOK_USERNAME,FBusername);
                e.putBoolean(PREF_KEY_FACEBOOK_LOGIN, true);
                e.putLong(GlobalSettings.PREF_KEY_LAST_SRV_UPDATE, 0); //Force updateDB on server
                e.commit(); // save changes 
				bttFB.setBackgroundResource(R.drawable.fb_icon);
				txtFBuser.setText("Logged in as " + FBusername);
				FBlogged = true;
			}
		}
		else{// do nothing and display error
			 alert.showAlertDialog(AddSocialActivity.this, "ESA Connection Error",
	                    "Error contacting the ESA Server. Try again later.", false);
		}
		if(dialog!=null)
		dialog.dismiss();
	}

            /**
             * Function to logout from the social network
             * It will  clear the application shared preferences and call DeleteToken 
             * */
            private void logoutFromTwitter() {
             
                dialog = ProgressDialog.show(AddSocialActivity.this, "", "Contacting Esa Server. Please, Wait...", true);
            	dialog.show();                   
                //Calling the webService for store the AccessToken
            	new DeleteToken(this).execute(esaUsrID, "Twitter");
            	new DeletePost(this).execute(esaUsrID, "Twitter");
              
            }  
            
            private void logoutFromFacebook() {
            	//fb.setAccessExpires(-1);
            	//fb.setAccessToken(null);
            	//fb.isSessionValid();

                if (Session.getActiveSession() != null)
                  Session.getActiveSession().closeAndClearTokenInformation();

                

                dialog = ProgressDialog.show(AddSocialActivity.this, "", "Contacting Esa Server. Please, Wait...", true);
            	dialog.show();                   
                //Calling the webService for store the AccessToken
            	new DeleteToken(this).execute(esaUsrID, "Facebook");
            	new DeletePost(this).execute(esaUsrID, "Facebook");
            } 
            
            @Override
            public void onBackPressed() {
                // TODO Auto-generated method stub
                super.onBackPressed();
                
            }
            
        	@Override
        	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        	  super.onActivityResult(requestCode, resultCode, data);
        	  Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        	  
        	}

        	
        	 /*
             * Callback when user has authorized the app with the new permissions
             */
            private final class LoginDialogListener implements DialogListener {
                @Override
                public void onComplete(Bundle values) {
                   
                   Log.e("Permission->", "OK!");
                }

                @Override
                public void onFacebookError(FacebookError error) {
                	 Log.e("Permission->", "KO: "+ error.getMessage());
                }

                @Override
                public void onError(DialogError error) {
                	Log.e("Permission->", "KO: "+ error.getMessage());
                }

                @Override
                public void onCancel() {
                    
                }
            }
            
    }

